home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Determining the length of an int in string form
- Date: Fri, 15 Mar 96 16:21:16 GMT
- Organization: none
- Message-ID: <826906876snz@genesis.demon.co.uk>
- References: <3146D058.DD7@cbm.com> <3147BE0D.296@hsc.unt.edu>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <3147BE0D.296@hsc.unt.edu>
- sfogoros@hsc.unt.edu "Steve Fogoros" writes:
-
- >Dave Payne wrote:
- >>
- >> Consider this:
- >>
- >> I have a variable of type int, and I would like to use the sprintf()
- >> function to write this variable to a string. However, I want to
- >> dynamically allocate the space for the string, and only malloc enough
- >> space to hold the int. Here's a code fragment that may illustrate this
- >> more clearly:
- >>
- >
- >Here is what I would do,
- >
- > char buf[80]; // int could be any length when converted. (Twenty years from
- > now
- > // will int be 256 bits? That would be over 80 digits.)
- > // In the mean time you should make buf at least buf[12] because
- > // int could be 32 bits. For 64 bit use buf[22];
-
- If you are writng C code you can't use // - it is a syntax error.
-
- There is no need to make buf an external declaration - it can be a local
- variable in func1().
-
- You can calculate a suitable size for buf e.g.
-
- #include <limits.h>
-
- #define INTBUF_SIZE (sizeof(int) * CHAR_BIT / 3 + 2)
-
- > void func1() {
- >
- > int i = 1234;
- > char *a;
- >
- > sprintf(buf,"%s%d","The value of i is ",i);
-
- And with the reduced buffer size we'd better make that:
-
- sprintf(buf,"%d",i);
-
- > a = malloc(strlen(buf + 1));
-
- Don't forget that sprintf returns the length of the string it writes, unless
- your system library is prehistoric.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-